package cn.wokoba.dao.adapter.port;


import cn.wokoba.dao.gateway.GroupBuyNotifyService;
import cn.wokoba.dao.gateway.GroupBuyRefundService;
import cn.wokoba.dao.redis.RedissonService;
import cn.wokoba.service.trade.adapter.port.ITradePort;
import cn.wokoba.service.trade.model.entity.GroupBuyRefundEntity;
import cn.wokoba.service.trade.model.entity.NotifyTaskEntity;
import cn.wokoba.types.enums.NotifyTaskHTTPEnumVO;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class TradePort implements ITradePort {

    @Resource
    private GroupBuyNotifyService groupBuyNotifyService;
    @Resource
    private GroupBuyRefundService groupBuyRefundService;
    @Resource
    private RedissonService redisService;

    @Override
    public String groupBuyNotify(NotifyTaskEntity notifyTask) throws Exception {
        RLock lock = redisService.getLock(notifyTask.lockKey());
        try {
            //避免被多次执行
            if (lock.tryLock(3, 0, TimeUnit.SECONDS)) {
                try {
                    // 无效的 notifyUrl 则直接返回成功
                    if (StringUtils.isBlank(notifyTask.getNotifyUrl()) || "暂无".equals(notifyTask.getNotifyUrl())) {
                        return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                    }
                    return groupBuyNotifyService.groupBuyNotify(notifyTask.getNotifyUrl(), notifyTask.getParameterJson());
                } finally {
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }
            }
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        } catch (Exception e) {
            Thread.currentThread().interrupt();
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }
    }

    @Override
    public String refundNotify(GroupBuyRefundEntity groupBuyRefundEntity) {
        RLock lock = redisService.getLock(groupBuyRefundEntity.lockKey());
        try {
            if (lock.tryLock(3, 0, TimeUnit.SECONDS)) {
                try {
                    return groupBuyRefundService.groupBuyRefund(JSON.toJSONString(groupBuyRefundEntity));
                } finally {
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }
            }
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        } catch (Exception e) {
            Thread.currentThread().interrupt();
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }
    }

}
